/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gps.general;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "gps_general")
@RequestScoped
public class Main extends Beans {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Vaiables de importación de otros modulos
    //Variables del modulo
    private Find gps_generalFind = new Find();
    private List<Beans> gps_generalList = new ArrayList<>();
    //Variables locales
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {
            map.clear();
            map.put("g.id = " + logged.getMasterId(), " ");

            gps_generalList.clear();
            gps_generalList = gps_generalFind.byMap(map);

            setId(gps_generalList.get(0).getId());
            setImei(gps_generalList.get(0).getImei());
            setNumero_serie(gps_generalList.get(0).getNumero_serie());
            setTelefono(gps_generalList.get(0).getTelefono());
            setMarca(gps_generalList.get(0).getMarca());
            setModelo(gps_generalList.get(0).getModelo());
            setNombre(gps_generalList.get(0).getNombre());
            setTipo(gps_generalList.get(0).getTipo());
            setDetalle(gps_generalList.get(0).getDetalle());
            setCaducidad(gps_generalList.get(0).getCaducidad());


        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            //se carga el mapa con los valores
            map.clear();
            map.put("lower(imei) = '" + getImei().toLowerCase() + "'", "  ");
            /*     map.put("lower(numero_serie) = '" + getNumero_serie().toLowerCase() + "'", " AND ");
             map.put("lower(marca) = '" + getMarca().toLowerCase() + "'", " AND ");
             map.put("lower(modelo) = '" + getModelo().toLowerCase() + "'", " AND ");
             map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " AND ");
             map.put("tipo = " + getTipo() , " AND ");
             map.put("lower(detalle) = '" + getDetalle().toLowerCase() + "'", "   ");*/

            //Verifica si el registro existe, de lo contrario lo inserta
            if (gps_generalFind.byExist(map)) {
                throw new Exc("m5");
            }
            sql = "INSERT INTO public.gps (imei, numero_serie, marca, modelo, nombre, tipo,detalle, caducidad,telefono) "
                    + "VALUES ('" + getImei() + "', '"
                    + getNumero_serie() + "' , "
                    + "'" + getMarca() + "', "
                    + "'" + getModelo() + "', "
                    + "'" + getNombre() + "', "
                    + " " + getTipo() + " , "
                    + "'" + getDetalle() + "', "
                    + "'" + getCaducidad() + "',"
                    + " '" + getTelefono() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            gps_generalList = gps_generalFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setMasterId(gps_generalList.get(0).getId());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            map.clear();
            map.put("g.id <> " + logged.getMasterId(), " AND ");
            map.put("lower(imei) = '" + getImei() + "'", "   ");

            /*map.put("lower(numero_serie) = '" + getNumero_serie().toLowerCase() + "'", " AND ");
             map.put("lower(marca) = '" + getMarca().toLowerCase() + "'", " AND ");
             map.put("lower(modelo) = '" + getModelo().toLowerCase() + "'", " AND ");
             map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " AND ");
             map.put("tipo = " + getTipo(), " AND ");
             map.put("lower(detalle) = '" + getDetalle().toLowerCase() + "'", " AND ");
             map.put("caducidad = '" + getCaducidad() + "'", "  ");*/
            //Verifica si el registro existe, de lo contrario lo inserta
            if (gps_generalFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.gps SET "
                    + "imei = '" + getImei() + "', "
                    + "numero_serie = " + getNumero_serie() + ", "
                    + "marca = '" + getMarca() + "', "
                    + "modelo = '" + getModelo() + "', "
                    + "nombre = '" + getNombre() + "', "
                    + "tipo = " + getTipo() + ", "
                    + "detalle = '" + getDetalle() + "', "
                    + "caducidad = '" + getCaducidad() + "', "
                    + "telefono = '" + getTelefono() + "' "
                    + "WHERE id = " + logged.getMasterId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }

    }

    public void delete() {
        try {
            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id
            deleteById(logged.getMasterId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        sql = "DELETE FROM public.gps "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        clearBeans();
        logged.setDetailId(0);
    }

    public void selectedTempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }

    //Permite mostrar los campos de acuerdo al rol 
    public boolean accesoRendered() {
        if (logged.getLoggedRol() == 1) {
            return true;
        }
        return false;
    }
    //Permite desactivar los campos de acuerdo  al rol

    public boolean acceso() {
        if (logged.getLoggedRol() == 1) {
            return false;
        }
        return true;

    }
}
